// 公共请求方法
const http = (Name, Data = {}) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('Token')
		// 判断是否存在token
		if (!token) {
			if (Name == 'getArticle') {
				uniCloud.callFunction({
					name: Name,
					data: Data,
					success: (res) => {
						resolve(res)
					},
					fail: (err) => {
						reject(err)
					}
				})
				return
			}
			uni.showToast({
				icon: 'error',
				title: '请先登录!',
				duration: 2000
			})
			// 返回登录页
			setTimeout(() => {
				uni.redirectTo({
					url: '/pages/login/login'
				})
			}, 2000)
		} else {
			// 用户已经登录(验证token合法性)
			uniCloud.callFunction({
				name: "verifyToken",
				data: {
					token: token,
				},
				success: (TokenRes) => {
					if (TokenRes.result === false) {
						// token 过期
						uni.showToast({
							icon: 'error',
							title: '登录失效',
							duration: 2000
						})
						// 返回登录页
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/login/login'
							})
						}, 2000)
					} else {
						let data = Object.assign(Data, {
							openid: TokenRes.result.data.result.openid
						})
						uniCloud.callFunction({
							name: Name,
							data: data,
							success: (res) => {
								resolve(res)
							},
							fail: (err) => {
								reject(err)
							}
						})

					}
				}
			})

		}

	})

}


export default http